//
//  LoginViewController.m
//  XDCommonApp
//
//  Created by XD-XY on 2/13/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "LoginViewController.h"
#import "XDTabBarViewController.h"
#import "UserInfo.h"
#import "XDTools.h"
#import "XDHeader.h"
#import "RegisterViewController.h"
#import "AppDelegate.h"
#import "ForgetViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
//    AppDelegate *delegate =  (AppDelegate *)[UIApplication sharedApplication].delegate;
//    delegate.window.alpha = .1;
    
	// Do any additional setup after loading the view.
    [self.leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    btn.backgroundColor = [UIColor grayColor];
    [btn setTitle:@"enter" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnclick) forControlEvents:UIControlEventTouchUpInside];
//    [self.contentView addSubview:btn];
   
    [self changgeContentViewFrame];
    [self initViews];
}
//初始化登录界面
-(void)initViews{
    if (!iPhone5) {
        self.contentView.frame = CGRectMake(0, 0, 320, 460);
    }
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width
                                                                     , self.contentView.frame.size.height)];
    _scrollView.scrollEnabled = NO;
    [self.contentView addSubview:_scrollView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelPan)];
    [self.contentView addGestureRecognizer:tap];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(113, 90, 100, 40)];
    titleLabel.text = @"用户登录";
    titleLabel.font = [UIFont fontWithName:@"Helvetica" size:22.0];
    titleLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:titleLabel];
    
    UILabel *registLabel = [[UILabel alloc] initWithFrame:CGRectMake(134,titleLabel.frame.origin.y+titleLabel.frame.size.height+20,60, 12)];
    registLabel.text = @"新用户注册";
    registLabel.font = [UIFont fontWithName:@"Helvetica" size:12.0];
    registLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:registLabel];
    
    //注册的透明btn
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registBtn.frame = CGRectMake(135, registLabel.frame.origin.y-5,registLabel.frame.size.width+10, registLabel.frame.size.height+10);
    [registBtn addTarget:self action:@selector(goRegist:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:registBtn];
    
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(registLabel.frame.origin.x, registLabel.frame.origin.y+registLabel.frame.size.height, registLabel.frame.size.width, 1)];
    lineView.backgroundColor = [UIColor blackColor];
    [self.scrollView addSubview:lineView];
    
    UILabel *zhLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, registLabel.frame.origin.y+registLabel.frame.size.height+50,42, 30)];
    zhLabel.text = @"账号：";
    zhLabel.font = [UIFont systemFontOfSize:14.0];
    zhLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:zhLabel];
    
    userTf = [[UITextField alloc] initWithFrame:CGRectMake(zhLabel.frame.origin.x+zhLabel.frame.size.width, zhLabel.frame.origin.y, 180, 30)];
    userTf.borderStyle = UITextBorderStyleLine;
    userTf.backgroundColor = RGBA(168, 168, 168, 1.0);
    userTf.placeholder = @"请输入您的账号";
    userTf.textColor = [UIColor whiteColor];
    if (IOS7) {
        userTf.tintColor = [UIColor whiteColor];

    }
    userTf.font = [UIFont systemFontOfSize:13.0];
//    userTf.keyboardType = UIKeyboardTypeNumberPad;
    userTf.delegate = self;
    userTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.scrollView addSubview:userTf];
    
    
    UILabel *pwdLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, zhLabel.frame.origin.y+registLabel.frame.size.height+35,42, 30)];
    pwdLabel.text = @"密码：";
    pwdLabel.font = [UIFont systemFontOfSize:14.0];
    pwdLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:pwdLabel];
    
    pwdTf = [[UITextField alloc] initWithFrame:CGRectMake(pwdLabel.frame.origin.x+pwdLabel.frame.size.width, pwdLabel.frame.origin.y, 180, 30)];
    pwdTf.borderStyle = UITextBorderStyleLine;
    pwdTf.backgroundColor =  RGBA(168, 168, 168, 1.0);
    if (IOS7) {
        pwdTf.tintColor = [UIColor whiteColor];
        
    }
    pwdTf.textColor = [UIColor whiteColor];
    pwdTf.secureTextEntry = YES;
    pwdTf.font = [UIFont systemFontOfSize:13.0];
    pwdTf.placeholder = @"请输入您的密码";
    pwdTf.returnKeyType = UIReturnKeyJoin;
    pwdTf.delegate = self;
    pwdTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.scrollView addSubview:pwdTf];
    
    
    //忘记密码
    UILabel *forgetLabel = [[UILabel alloc] initWithFrame:CGRectMake(pwdTf.frame.origin.x+pwdTf.frame.size.width-50,pwdTf.frame.origin.y+pwdTf.frame.size.height+10,51, 13)];
    forgetLabel.text = @"忘记密码";
    forgetLabel.font = [UIFont systemFontOfSize:12.0];
    forgetLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:forgetLabel];
    
    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(forgetLabel.frame.origin.x, forgetLabel.frame.origin.y+forgetLabel.frame.size.height, forgetLabel.frame.size.width, 1)];
    lineView1.backgroundColor = [UIColor blackColor];
    [self.scrollView addSubview:lineView1];
    
    //忘记密码透明按钮
    UIButton *forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetBtn.frame = CGRectMake(forgetLabel.frame.origin.x-5, forgetLabel.frame.origin.y-5,forgetLabel.frame.size.width+10, forgetLabel.frame.size.height+10);
    [forgetBtn addTarget:self action:@selector(goForgetCode:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:forgetBtn];
    
    
    UILabel *continueLabel = [[UILabel alloc] initWithFrame:CGRectMake(135, lineView1.frame.origin.y+lineView1.frame.size.height+10, 30,15)];
    continueLabel.text = @"登录";
    continueLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0];
    continueLabel.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:continueLabel];
    
    UIImageView *arImageView = [[UIImageView alloc] initWithFrame:CGRectMake(continueLabel.frame.origin.x+continueLabel.frame.size.width+6, continueLabel.frame.origin.y-2, 12, 18)];
    arImageView.image = [UIImage imageNamed:@"launh_sure"];
    [self.scrollView addSubview:arImageView];
    
    UIButton *launchBtn = [UIButton buttonWithType:UIButtonTypeCustom];


    launchBtn.frame = CGRectMake(130, lineView1.frame.origin.y+lineView1.frame.size.height+5, 50, 30);
    [launchBtn addTarget:self action:@selector(goLaunch) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:launchBtn];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(8, 0, 45, 45);
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *bImageView = [[UIImageView alloc] initWithFrame:CGRectMake(24, 17, 11, 18)];
    bImageView.image = [UIImage imageNamed:@"left_back"];
    [self.scrollView addSubview:bImageView];
    [self.scrollView addSubview:backBtn];
    
    
    
}
//点击登录按钮
-(void)goLaunch{
    [self cancelPan];
    if (userTf.text.length == 0||pwdTf.text.length == 0) {
        [XDTools showTips:@"内容不能为空" toView:self.contentView];
    }else{
//        [XDTools showTips:@"点到了" toView:self.contentView];

       [self getLaunchDatas];
    }
    


}
//调用登录接口
-(void)getLaunchDatas{



   NSString *body = [NSString stringWithFormat:@" <Login xmlns=\"http://tempuri.org/\">"
            "<phone>%@</phone>"
            "<password>%@</password>"
            "</Login>",userTf.text,pwdTf.text];
   
    __block ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:LOGIN];

    if([XDTools NetworkReachable]){

        [request setCompletionBlock:^{
            
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
           // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                DDLOG(@"result  ---=%@",result);
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                DDLOG(@"respodic = %@",responseDict);
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    [XDTools showTips:@"登录成功" toView:self.contentView];
                    NSString *uid = [NSString stringWithFormat:@"%@",[responseDict objectForKey:@"uid"]];
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//                    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:3];
                    [user setObject:uid forKey:kMY_USER_ID];
                    [user setObject:userTf.text forKey:kMY_USER_NAME];
                    [user setObject:userTf.text forKey:@"phone"];
                    [user setObject:pwdTf.text forKey:kMY_USER_PASSWORD];
                    DDLOG(@"UID = %@",[user valueForKey:kMY_USER_PASSWORD]);
//                    [user setObject:dic forKey:kMY_USERINFO];
                    [self performSelector:@selector(btnclick) withObject:nil afterDelay:1.0];
                }else{
                    [XDTools showTips:@"登录失败" toView:self.contentView];
                }
                

            }

            
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            //        NSError *error = [request error];
            [XDTools showTips:@"nimei" toView:self.contentView];
        }];
        //[XDTools showProgress:self.contentView];
        [request startAsynchronous];
        
//        [XDTools showTips:@"nimeiaaaaaa" toView:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }

}

-(void)getLaunchDatasJiade{
    for (UIButton * button in [[XDTabBarViewController sharedXDTabBarViewController].bgView subviews]){
        if ([button isKindOfClass:[UIButton class]]){
            if (button.tag == 10001+3){
                [button setBackgroundImage:[UIImage imageNamed:@"tab_button%d_notOn"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"tab_button%d_on"] forState:UIControlStateHighlighted];
                [button setBackgroundImage:[UIImage imageNamed:@"tab_button%d_on"] forState:UIControlStateDisabled];
                button.adjustsImageWhenHighlighted =NO;
            }
        }
    }
    
    NSString *body = [NSString stringWithFormat:@" <Login xmlns=\"http://tempuri.org/\">"
                      "<phone>%@</phone>"
                      "<password>%@</password>"
                      "</Login>",userTf.text,pwdTf.text];
    
    __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:LOGIN];
    if([XDTools NetworkReachable]){
        [request setCompletionBlock:^{
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                DDLOG(@"result  ---=%@",result);
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                DDLOG(@"respodic = %@",responseDict);
                if ([[responseDict objectForKey:@"code"] intValue]==0){
                    [XDTools showTips:@"登录成功" toView:self.contentView];
                    NSString *uid = [NSString stringWithFormat:@"%@",[responseDict objectForKey:@"uid"]];
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                    //                    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:3];
                    [user setObject:uid forKey:kMY_USER_ID];
                    [user setObject:userTf.text forKey:kMY_USER_NAME];
                    [user setObject:pwdTf.text forKey:kMY_USER_PASSWORD];
                    DDLOG(@"UID = %@",[user valueForKey:kMY_USER_PASSWORD]);
                    //                    [user setObject:dic forKey:kMY_USERINFO];
                    [self performSelector:@selector(btnclick) withObject:nil afterDelay:1.0];
                }else{
                    [XDTools showTips:@"登录失败" toView:self.contentView];
                }
                
                
            }
            
            
        }];
        
        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            //        NSError *error = [request error];
            [XDTools showTips:@"nimei" toView:self.contentView];
        }];
        //[XDTools showProgress:self.contentView];
        [request startAsynchronous];
        
        //        [XDTools showTips:@"nimeiaaaaaa" toView:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
    
}
//注册
-(void)goRegist:(UIButton *)sender{
    [self cancelPan];
    RegisterViewController *registVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registVC animated:YES];
   
}
//忘记密码
-(void)goForgetCode:(UIButton *)sender{
    ForgetViewController *forgetVC = [[ForgetViewController alloc] init];
    [self.navigationController pushViewController:forgetVC animated:YES];
     DDLOG(@"aaaa");
}
//uitextfield代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self goLaunch];
    return YES;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

        [UIView animateWithDuration:.3 animations:^{
            self.scrollView.contentOffset = CGPointMake(0, 90);
        }];

    
    return  YES;
}
-(void)btnclick
{
    for (UIButton * button in [[XDTabBarViewController sharedXDTabBarViewController].bgView subviews]){
        if ([button isKindOfClass:[UIButton class]]){
            if (button.tag == 10001+3){
                [button setBackgroundImage:[UIImage imageNamed:@"tab_button4_not_Launch"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"tab_button4_not_Launch"] forState:UIControlStateHighlighted];
                [button setBackgroundImage:[UIImage imageNamed:@"tab_button4_launch"] forState:UIControlStateDisabled];
                button.adjustsImageWhenHighlighted =NO;
            }
        }
    }
    
    [[UserInfo sharedUserInfo] setIsLogin:YES];
    NSInteger selectIndex = [XDTabBarViewController sharedXDTabBarViewController].presentIndex;
    NSInteger lastIndex = [XDTabBarViewController sharedXDTabBarViewController].beforeIndex;
    if ([[NEEDACCOUNTFORLOGIN objectAtIndex:selectIndex] isEqualToString:@"1"]){
        if ([UserInfo sharedUserInfo].isLogin){
            [[XDTabBarViewController sharedXDTabBarViewController] setSelectedIndex:selectIndex];
            [[XDTabBarViewController sharedXDTabBarViewController] confirmSelectTabBar:selectIndex];
        }else{
            [[XDTabBarViewController sharedXDTabBarViewController] setSelectedIndex:lastIndex];
            [[XDTabBarViewController sharedXDTabBarViewController] confirmSelectTabBar:lastIndex];
        }
    }
    [self back];
}

-(void)cancelPan{
    [userTf resignFirstResponder];
    [pwdTf resignFirstResponder];
    [UIView animateWithDuration:.3 animations:^{
        self.scrollView.contentOffset = CGPointMake(0, 0);
    }];
}

-(void)back
{
    NSInteger selectIndex = [XDTabBarViewController sharedXDTabBarViewController].presentIndex;
    if ([[NEEDACCOUNTFORLOGIN objectAtIndex:selectIndex] isEqualToString:@"1"]){
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
